package org.example.managementsystem.service;

import org.example.managementsystem.model.Material;
import org.example.managementsystem.repository.MaterialDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 物料信息服务层
 */
@Service
public class MaterialService {
    private final MaterialDao materialDao;

    @Autowired
    public MaterialService(MaterialDao materialDao) {
        this.materialDao = materialDao;
    }

    /**
     * 添加物料
     */
    public Material addMaterial(Material material) {
        // 确保物料编号为空，以便后续自动生成
        material.setMaterialNumber(null);

        // 先插入获取ID
        Long id = materialDao.insertMaterial(material);
        material.setId(id);

        // 根据物料类型和ID生成编号
        String typeAbbr = getMaterialTypeAbbr(material.getType());
        String materialNumber = typeAbbr + id;
        material.setMaterialNumber(materialNumber);

        // 更新物料编号
        materialDao.updateMaterial(material);

        return material;
    }

    /**
     * 批量更新空物料编号
     */
    public int batchUpdateEmptyMaterialNumbers() {
        return materialDao.batchUpdateEmptyMaterialNumbers();
    }

    /**
     * 获取物料类型缩写
     */
    private String getMaterialTypeAbbr(String type) {
        switch (type) {
            case "金属": return "JS";
            case "合金": return "HJ";
            case "复合材料": return "FH";
            default: return "QT"; // 其他情况
        }
    }

    /**
     * 更新物料信息
     */
    public boolean updateMaterial(Material material) {
        // 如果物料编号为空，获取原有物料信息的编号
        if (material.getMaterialNumber() == null || material.getMaterialNumber().isEmpty()) {
            Material existingMaterial = materialDao.getMaterialById(material.getId());
            if (existingMaterial != null) {
                material.setMaterialNumber(existingMaterial.getMaterialNumber());
            } else {
                // 如果找不到原有物料，根据类型生成新编号
                String typeAbbr = getMaterialTypeAbbr(material.getType());
                String materialNumber = typeAbbr + material.getId();
                material.setMaterialNumber(materialNumber);
            }
        }
        return materialDao.updateMaterial(material) > 0;
    }

    /**
     * 删除物料
     */
    public boolean deleteMaterial(Long id) {
        return materialDao.deleteMaterial(id) > 0;
    }

    /**
     * 根据ID查询物料
     */
    public Material getMaterialById(Long id) {
        return materialDao.getMaterialById(id);
    }

    /**
     * 根据供货商查询物料
     */
    public List<Material> getMaterialsByProvider(String providerName) {
        return materialDao.getMaterialsByProvider(providerName);
    }

    /**
     * 查询所有物料
     */
    public List<Material> getAllMaterials() {
        return materialDao.getAllMaterials();
    }

    /**
     * 搜索物料
     */
    public List<Material> searchMaterials(String keyword) {
        return materialDao.searchMaterials(keyword);
    }


}
